package gpl.pierrick.brihaye.aramorph;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Loads a dictionary from an XML file.
 * @author Ahmed Saad
 */
public class XMLCompatibilityLoader extends DefaultHandler {
	/**First part in the compatibility*/
	String first;
	/**Second part in the compatibility*/
	String second;
	/**The current location in the XML file*/
	private int location;
	/**The compatability table to be loaded*/
	private final InMemoryCompatibilityTable table;

	/**
	 * Creates a new CompatabilityLoader that will load the passed comptatibility table.
	 * @param ct the compatiblity table to be loaded. This must have been constructed and may not be null.
	 */
	public XMLCompatibilityLoader(InMemoryCompatibilityTable ct) {
		this.table = ct;
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		String value = new String(ch,start,length).trim();
		if (value.length() == 0)
			return;
		switch (location) {
		case 1: first = value; break;
		case 2: second = value; break;
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (location == 2) {
			//signal a completed entry loaded
			entryLoaded(first,second);
		}
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (qName.equals("entry"))
			location = 0;
		else if (qName.equals("prefix") || qName.equals("suffix") || qName.equals("stem"))
			location++;
	}
	
	protected void entryLoaded(String first, String second) {
		table.addCompatabilityEntry(first,second);
	}
}